#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "open.h"

#define MAXLINE     8192

int main(int argc, char *argv[])
{
    int clientfd, port;
    char *host, buf[MAXLINE];
    FILE *f;
    
    if (argc != 3)
    {
        printf("usage: %s <host><port>\n", argv[0]);
        exit(0);
    }

    host = argv[1];
    port = atoi(argv[2]);

    clientfd = open_clientfd(host, port);
    if (clientfd < 0)
    {
        perror("open client fd error");
        exit(0);
    }

    f = fdopen(clientfd, "r+");
    if (f == NULL)
    {
        perror("fdopen error");
        exit(0);
    }

    /* send request */
    sprintf(buf, "GET / HTTP/1.1\r\n");
    sprintf(buf, "%sHost: %s:%d\r\n", buf, host, port);

    while(fgets(buf, MAXLINE, stdin) != NULL)
    {
        //fwrite(buf, 1, strlen(buf), f); 
        //fflush(f);
        //fread(buf, 1, MAXLINE, f);
        write(clientfd, buf, strlen(buf));
        read(clientfd, buf, MAXLINE);
        fputs(buf, stdout);
    }

    close(clientfd);

    return 0;
}
